package cn.xkai.general;

/**
 * @description: 二分查找算法（针对有序集合）
 * @author: kaixiang
 * @date: 2022-07-29
 **/
public class BinarySearch {
    public int binarySearch(int[] nums, int target) {
        int left = 0, right = nums.length - 1, mid, index = -1;
        while (left < right) {
            mid = (left + right) >>> 1;
            if (nums[mid] > target) {
                right = mid - 1;
            } else if (nums[mid] < target) {
                left = mid + 1;
            } else {
                return mid;
            }
        }
        return index;
    }
}
